package cn.fl.mcr.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import cmm.mid.core.framework.constant.tripartite.InterfaceConstants;
import cmm.mid.core.framework.constant.tripartite.InterfaceConstants.AuditResult;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.dto.MessageDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.dto.SysUsrDatAuthRDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.vo.AssTrailCarChannelVO;
import cn.fl.capital.condition.CapFundVfDtlQueryCondition;
import cn.fl.capital.dto.CapFundVfDtlDTO;
import cn.fl.capital.dto.VehLoanDTO;
import cn.fl.capital.service.ICapFundSummaryService;
import cn.fl.capital.service.ICapFundVfDtlApiService;
import cn.fl.capital.service.IVehLoanInstallmentApiService;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.constant.McrBillMConstant;
import cn.fl.mcr.service.IMcrBillMService;
import cn.fl.mcr.service.IMcrWaitBuyBackService;
import cn.fl.mcr.transform.McrBillMVOTransform;
import cn.fl.mcr.transform.McrLoanAccountVOTransform;
import cn.fl.mcr.transform.McrLoanChannelVOTransform;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.mcr.vo.McrLoanAccountVO;
import cn.fl.mcr.vo.McrLoanChannelVO;
import cn.fl.mcr.vo.McrWaitBuyBackVO;
import cn.fl.mcr.vo.UploadFilesManageVo;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.CapOverdueDtlCondition;
import cn.lionbridgecapital.loan.model.condition.McrBillBuyBackRecordQC;
import cn.lionbridgecapital.loan.model.condition.McrBillDQC;
import cn.lionbridgecapital.loan.model.condition.McrBillMQC;
import cn.lionbridgecapital.loan.model.condition.McrInformTransferQC;
import cn.lionbridgecapital.loan.model.condition.McrLoanAccountQC;
import cn.lionbridgecapital.loan.model.condition.McrLoanChannelQC;
import cn.lionbridgecapital.loan.model.condition.McrLoanRecQc;
import cn.lionbridgecapital.loan.model.condition.McrWaitBuyBackQC;
import cn.lionbridgecapital.loan.model.constant.McrCstCrLimConstant;
import cn.lionbridgecapital.loan.model.dto.CapOverdueInfoBean;
import cn.lionbridgecapital.loan.model.dto.McrBillBuyBackRecordDTO;
import cn.lionbridgecapital.loan.model.dto.McrBillDDTO;
import cn.lionbridgecapital.loan.model.dto.McrBillMDTO;
import cn.lionbridgecapital.loan.model.dto.McrInformTransferDTO;
import cn.lionbridgecapital.loan.model.dto.McrLoanAccountDTO;
import cn.lionbridgecapital.loan.model.dto.McrLoanRecDTO;
import cn.lionbridgecapital.loan.model.utils.DateUtils;
import cn.lionbridgecapital.loan.model.utils.LoanUtils;
import cn.lionbridgecapital.loan.service.api.IMcrBillBuyBackRecordApiService;
import cn.lionbridgecapital.loan.service.api.IMcrBillDApiService;
import cn.lionbridgecapital.loan.service.api.IMcrBillMApiService;
import cn.lionbridgecapital.loan.service.api.IMcrCstCrLimApiService;
import cn.lionbridgecapital.loan.service.api.IMcrInformTransferApiService;
import cn.lionbridgecapital.loan.service.api.IMcrLoanAccountApiService;
import cn.lionbridgecapital.loan.service.api.IMcrLoanChannelApiService;
import cn.lionbridgecapital.loan.service.api.IMcrLoanRecApiService;
import fl.yntrust.facade.api.IYnTrustApi;
import fl.yntrust.facade.dto.CapOverdueDtlDTO;
import fl.yntrust.facade.dto.RepurchaseDTO;
import fl.yntrust.facade.dto.RepurchaseDetail;
import fl.yntrust.facade.dto.UploadFilesManageDTO;
import net.sf.json.JSONArray;
import pam.wkxt.facade.api.IWkxtApiService;
import pam.wkxt.facade.dto.PrepaymentDTO;
import pay.business.facade.custpay.api.ICmmInstallmentApiService;

/**
 * @Description: 小贷账单主表 控制层
 */
@Controller
@RequestMapping("/mcr/mcrBillM")
public class McrBillMController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(McrBillMController.class);

    /**
     * McrBillM 服务层BEAN
     */
    @Autowired
    private IMcrBillMService mcrBillMService;
    @Autowired
    private IMcrBillMApiService publicMcrBillMApiService ;
    @Autowired
    private ICapFundSummaryService capFundSummaryService;
    @Autowired
    private IMcrBillDApiService publicMcrBillDApiService;
    @Autowired
    private IMcrInformTransferApiService publicMcrInformTransferApiService;
    @Autowired
    private ICapFundVfDtlApiService capFundVfDtlApiService;
    
    /**
     * 附件服务
     */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;
    
    @Autowired
    private IMcrLoanAccountApiService publicMcrLoanAccountApiService;
    @Autowired
    private IMcrLoanChannelApiService publicMcrLoanChannelApiService;
    @Autowired
	private IYnTrustApi ynTrustApi;
    @Autowired
    private ICstBscInfoService cstBscInfoService;
    @Autowired
    private IPriorityApiService priorityApiService;
    @Autowired
    private IMcrCstCrLimApiService publicMcrCstCrLimApiService;
    @Autowired
    private IWkxtApiService wkxtApiService;
    @Autowired
    private IMcrWaitBuyBackService mcrWaitBuyBackService;
    @Autowired
    private IMcrLoanRecApiService publicMcrLoanRecApiService;
    @Autowired
    private ICmmInstallmentApiService cmmInstallmentApiService;
    @Autowired
    private IVehLoanInstallmentApiService vehLoanInstallmentApiService;
    @Autowired
    private IMcrBillBuyBackRecordApiService mcrBillBuyBackRecordApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMList");

        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        List<KeyValueVO> loanStsCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        //贷款状态
        mav.addObject("loanStsCdList", JSON.toJSONString(loanStsCdList));
        
        //资方渠道
        McrLoanChannelQC channelQc = new McrLoanChannelQC();
        List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(channelQc));
        mav.addObject("channelList", channelList);
        //资方账户
        McrLoanAccountQC accountQc = new McrLoanAccountQC();
        List<McrLoanAccountVO> accountList = McrLoanAccountVOTransform.toVOList(publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(accountQc));
        mav.addObject("accountList", accountList);

        return mav;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListLgsPage.do", method = {RequestMethod.GET})
    public ModelAndView toListLgsPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListLgsPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMLgsList");

        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        List<KeyValueVO> loanStsCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        //贷款状态
        mav.addObject("loanStsCdList", JSON.toJSONString(loanStsCdList));

        //资方渠道
        McrLoanChannelQC channelQc = new McrLoanChannelQC();
        List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(channelQc));
        mav.addObject("channelList", channelList);
        //资方账户
        McrLoanAccountQC accountQc = new McrLoanAccountQC();
        List<McrLoanAccountVO> accountList = McrLoanAccountVOTransform.toVOList(publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(accountQc));
        mav.addObject("accountList", accountList);

        return mav;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toLisOutLoanPage.do", method = {RequestMethod.GET})
    public ModelAndView toLisOutLoanPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMOutList");

        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        List<KeyValueVO> loanStsCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        //贷款状态
        mav.addObject("loanStsCdList", JSON.toJSONString(loanStsCdList));

        //资方渠道
        McrLoanChannelQC channelQc = new McrLoanChannelQC();
        List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(channelQc));
        mav.addObject("channelList", channelList);
        //资方账户
        McrLoanAccountQC accountQc = new McrLoanAccountQC();
        List<McrLoanAccountVO> accountList = McrLoanAccountVOTransform.toVOList(publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(accountQc));
        mav.addObject("accountList", accountList);

        return mav;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toManLoanProcessingPage.do", method = {RequestMethod.GET})
    public ModelAndView toManLoanProcessingPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMManList");

        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        List<KeyValueVO> loanStsCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        //贷款状态
        mav.addObject("loanStsCdList", JSON.toJSONString(loanStsCdList));

        //资方渠道
        McrLoanChannelQC channelQc = new McrLoanChannelQC();
        List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(channelQc));
        mav.addObject("channelList", channelList);
        //资方账户
        McrLoanAccountQC accountQc = new McrLoanAccountQC();
        List<McrLoanAccountVO> accountList = McrLoanAccountVOTransform.toVOList(publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(accountQc));
        mav.addObject("accountList", accountList);

        return mav;
    }


    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initMcrBillMList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        McrBillMQC qc = new McrBillMQC();
        //设置查询条件？
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotBlank(cstNm)) {
            qc.setCstNm(cstNm);
        }
        String cstId = request.getParameter("cstId");
        if (StringUtils.isNotBlank(cstId)) {
            qc.setCstId(Long.valueOf(cstId));
        }
        String crCntNo = request.getParameter("crCntNo");
        if(StringUtils.isNotBlank(crCntNo)){
            qc.setCrCntNo(crCntNo);
        }
        String loanBizTypCd = request.getParameter("loanBizTypCd");
        if(StringUtils.isNotBlank(loanBizTypCd)){
            qc.setLoanBizTypCd(loanBizTypCd);
        }
        String loanStsCd = request.getParameter("loanStsCd");
        if(StringUtils.isNotBlank(loanStsCd)){
            qc.setLoanStsCd(loanStsCd);
        }
        String crTypCd = request.getParameter("crTypCd");
        if(StringUtils.isNotBlank(crTypCd)){
            qc.setCrTypCd(crTypCd);
        }
        String loanId = request.getParameter("loanId");
        String accountId = request.getParameter("accountId");
        if(StringUtils.isNotEmpty(loanId)){
        	qc.setLoanId(Long.parseLong(loanId));
        } 
        if(StringUtils.isNotEmpty(accountId)){
        	 qc.setLoanAccountId(Long.parseLong(accountId));
        }
        String isInform = request.getParameter("isInform");
        if(StringUtils.isNotEmpty(isInform)){
            qc.setIsInform(Integer.parseInt(isInform));
        }
        qc.setOpUsrId(CurrentThreadContext.getCurrentUserId());
        String cstTypeCd = request.getParameter("cstTypeCd");
        if(StringUtils.isNotEmpty(cstTypeCd)){
            if(cstTypeCd.equals("0")){
                List<String> cstTypes = new ArrayList<String>();
                cstTypes.add("0");
                cstTypes.add("3");
                qc.setCstTypeCdList(cstTypes);
                qc.setOrgCdType("1");
            }else{
                qc.setCstTypCd(cstTypeCd);
            }
        }
        String cstTypeCdList = request.getParameter("cstTypeCdList");
        BaseLogUtils.info(logger,"initMcrBillMList","初始化McrBillM列表页面数据.外部小贷请求参数.cstTypeCdList:"+cstTypeCdList);
        if(StringUtils.isNotEmpty(cstTypeCdList)){
            String[] split = cstTypeCdList.split(",");
            List<String> strings = Arrays.asList(split);
            qc.setCstTypeCdList(strings);
        }

        String remarkCode = request.getParameter("remarkCode");
        if(StringUtils.isNotEmpty(remarkCode)){
            qc.setRemarkCode(remarkCode);
        }

        try {
            //需要权限
            List<SysUsrDatAuthRDTO> usrDatAuthRList = this.priorityApiService.searchSysUsrDatAuthRWithOrgCdList(CurrentThreadContext.getCurrentUserId(),null,CurrentThreadContext.getCurrentSysCd());
            if(CollectionUtils.isNotEmpty(usrDatAuthRList)){
                qc.setUsrDatAuthRList(usrDatAuthRList);
            }
            BaseLogUtils.info(logger, "initMcrBillMList", "初始化McrBillM列表页面数据.获取权限:" + JSONObject.toJSONString(usrDatAuthRList), CurrentThreadContext.getCurrentUserName());
        } catch (Exception e) {
            BaseLogUtils.info(logger, "initMcrBillMList", "获取用户数据权限失败!" + e.getMessage());
        }
        
        String overDays = request.getParameter("overDays");//新增逾期天数
        if(StringUtils.isNotEmpty(overDays)) {
        	qc.setOverDays(Long.valueOf(overDays));
        }
        String repSts = request.getParameter("repSts");//回购状态
        if(StringUtils.isNotEmpty(repSts)) {
        	qc.setRepSts(repSts);
        }
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initMcrBillMList", "初始化McrBillM列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.mcrBillMService.searchListPage(page);
        List<McrBillMVO> list = (List<McrBillMVO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(list)){
        	for(McrBillMVO vo : list){
        		if(vo.getLoanAccountId()!=null){
        			McrLoanAccountDTO mcrLoanAccountDTO = this.publicMcrLoanAccountApiService.selectMcrLoanAccountDTOById(vo.getLoanAccountId());
        			vo.setAccountName(mcrLoanAccountDTO.getAccountName());
        		}
        	}
        }
        ListPageVO<McrBillMVO> listPage = new ListPageVO<McrBillMVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getMcrBillMById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getMcrBillMById", "获取McrBillM数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            McrBillMVO vo = this.mcrBillMService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getMcrBillMById", "获取McrBillM数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getMcrBillMById", "获取McrBillM数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getMcrBillMById", "获取McrBillM数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getMcrBillMById", "获取McrBillM数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toBillDtlPage.do", method = {RequestMethod.GET})
    public ModelAndView toBillDtlPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.info(logger, "toListPage", "加载McrBillM详情页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillDtl");
        String id = request.getParameter("id");
        if(StringUtils.isNotEmpty(id)){
            McrBillMVO vo = this.mcrBillMService.selectById(Long.valueOf(id));
            if (null != vo) {
                mav.addObject("mcrBillMVO",vo);
            }
            mav.addObject("billId",id);
        }
        return mav;
    }
    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private McrBillMVO getRequestParamForMcrBillM(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String cstId = request.getParameter("cstId");//客户ID
        String cstNm = request.getParameter("cstNm");//客户名称
        String crCntNo = request.getParameter("crCntNo");//贷款合同号
        String crAmt = request.getParameter("crAmt");//贷款金额
        String actCrAmt = request.getParameter("actCrAmt");//实际放款金额
        String loanBizTypCd = request.getParameter("loanBizTypCd");//业务类型（MCR0007）
        String crTypCd = request.getParameter("crTypCd");//贷款类型（MCR0001）
        String crPd = request.getParameter("crPd");//租赁期数
        String crPdUntCd = request.getParameter("crPdUntCd");//贷款期数单位（MCR0003）
        String rateTypCd = request.getParameter("rateTypCd");//计息方式（MCR0002）
        String crRatePct = request.getParameter("crRatePct");//贷款日利率（%）
        String rntAmt = request.getParameter("rntAmt");//每期租金
        String crDt = request.getParameter("crDt");//放款日
        String loanStsCd = request.getParameter("loanStsCd");//贷款状态（MCR0005）
        String crLvlCd = request.getParameter("crLvlCd");//信用等级（MCR0004）
        String crLimAmt = request.getParameter("crLimAmt");//信用额度
        String totLoanAmt = request.getParameter("totLoanAmt");//已用额度
        String totRetAmt = request.getParameter("totRetAmt");//累计归还额度
        String specStsCd = request.getParameter("specStsCd");//专款专用状态（MCR0009）

        //验证参数并赋值
        McrBillMVO entity = new McrBillMVO();
        //entity.setCstId(cstId);//客户ID
        //entity.setCstNm(cstNm);//客户名称
        //entity.setCrCntNo(crCntNo);//贷款合同号
        //entity.setCrAmt(crAmt);//贷款金额
        //entity.setActCrAmt(actCrAmt);//实际放款金额
        //entity.setLoanBizTypCd(loanBizTypCd);//业务类型（MCR0007）
        //entity.setCrTypCd(crTypCd);//贷款类型（MCR0001）
        //entity.setCrPd(crPd);//租赁期数
        //entity.setCrPdUntCd(crPdUntCd);//贷款期数单位（MCR0003）
        //entity.setRateTypCd(rateTypCd);//计息方式（MCR0002）
        //entity.setCrRatePct(crRatePct);//贷款日利率（%）
        //entity.setRntAmt(rntAmt);//每期租金
        //entity.setCrDt(crDt);//放款日
        //entity.setLoanStsCd(loanStsCd);//贷款状态（MCR0005）
        //entity.setCrLvlCd(crLvlCd);//信用等级（MCR0004）
        //entity.setCrLimAmt(crLimAmt);//信用额度
        //entity.setTotLoanAmt(totLoanAmt);//已用额度
        //entity.setTotRetAmt(totRetAmt);//累计归还额度
        //entity.setSpecStsCd(specStsCd);//专款专用状态（MCR0009）

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
        }

        return entity;
    }


    /*******************************
     * 到小贷逾期账单列表页面
     *******************************/
    @RequestMapping(value = "/toMcrOvdBillListPage.do", method = {RequestMethod.GET})
    public ModelAndView toMcrOvdBillListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toOvdListPage", "加载到小贷逾期账单列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView();
        mav.setViewName("mcr/mcrBillM/mcrOvdBillList");
        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        return mav;
    }

    /*******************************
     * 初始化小贷逾期账单列表
     *******************************/
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initMcrOvdBillList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initMcrOvdBillList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        McrBillMQC qc = new McrBillMQC();
        //设置查询条件？
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotBlank(cstNm)) {
            qc.setCstNm(cstNm);
        }
        String crCntNo = request.getParameter("crCntNo");
        if(StringUtils.isNotBlank(crCntNo)){
            qc.setCrCntNo(crCntNo);
        }
        String loanBizTypCd = request.getParameter("loanBizTypCd");
        if(StringUtils.isNotBlank(loanBizTypCd)){
            qc.setLoanBizTypCd(loanBizTypCd);
        }
        String loanStsCd = request.getParameter("loanStsCd");
        if(StringUtils.isNotBlank(loanStsCd)){

        }
        String crTypCd = request.getParameter("crTypCd");
        if(StringUtils.isNotBlank(crTypCd)){
            qc.setCrTypCd(crTypCd);
        }
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        qc.setLoanStsCd(McrBillMConstant.LOAN_STS_CD_4);
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initMcrBillMList", "初始化McrBillM列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.mcrBillMService.searchOvdListPage(page);
        List<McrBillMVO> list = (List<McrBillMVO>) pager.getResultList();
        ListPageVO<McrBillMVO> listPage = new ListPageVO<McrBillMVO>(list, pager.getTotalCount());
        return listPage;
    }
  
    //-------------------------批量图片上传
    
    /**
     * 批量图片上传列表页面
     */
    @RequestMapping(value = "/picUploadListPage.do", method = {RequestMethod.GET})
    public ModelAndView picUploadListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMPicList");

        //资方渠道
        McrLoanChannelQC channelQc = new McrLoanChannelQC();
        List<McrLoanChannelVO> channelList = McrLoanChannelVOTransform.toVOList(publicMcrLoanChannelApiService.searchMcrLoanChannelDTOList(channelQc));
        mav.addObject("channelList", channelList);
        //资方账户
        McrLoanAccountQC accountQc = new McrLoanAccountQC();
        List<McrLoanAccountVO> accountList = McrLoanAccountVOTransform.toVOList(publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(accountQc));
        mav.addObject("accountList", accountList);
        return mav;
    }
    
    
    /**
	 * 新增
	 */
	@RequestMapping(value = "/uploadPic.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String idS = request.getParameter("ids");//主键ID
		String attchmnt = request.getParameter("fileParams");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AssTrailCarChannelVO entity = null;
		try {
	        JSONArray files = JSONArray.fromObject(attchmnt);
	        final JSONArray ids = JSONArray.fromObject(idS);
	        if(null != files && !files.isEmpty() && files.isArray()){
	        	if(files.size()<ids.size()){
	        		result.setSuccess(BaseConstant.IS_YESNO_NO);
		            result.setInfo("上传图片数量不能小于账单数量");
		            return result;
	        	}else{
	        		for (int i = 0; i < ids.size(); i++) {
	        			if (StringUtils.isNotEmpty(ids.get(i).toString())) {
	   		                uploadAttchment(files.get(i).toString(), result, Long.valueOf(ids.get(i).toString()));
	   		            }
					}
	        		new Thread(){
	        			public void run(){
	        				for (int i = 0; i < ids.size(); i++) {
	        					if (StringUtils.isNotEmpty(ids.get(i).toString())) {
	    	   		               	McrBillMVO vo = mcrBillMService.selectById(Long.valueOf(ids.get(i).toString()));
	    	   		               	if(!"1".equals(vo.getUploadStsCd())){
		    	   		               	try {
			    	   		               	MessageDTO<String> message = ynTrustApi.uploadFile(vo.getLoanId(), vo.getId(), vo.getCstId());
			    	   		               	BaseLogUtils.info(logger, "uploadFile", "调用云信上传发票接口返回数据:" + JSONObject.toJSONString(message), CurrentThreadContext.getCurrentUserName());
			    	   		               	if(message.isSuccess()){
			    	   		               		vo.setUploadStsCd("1");
                                                publicMcrBillMApiService.modifyMcrBillM(McrBillMVOTransform.toDTO(vo));
			    	   		               	}
			    	   		             } catch (Exception e) {
			    	 						BaseLogUtils.error(logger, "uploadBillM","调用云信上传发票接口异常："+e.getMessage());
			    	 						continue;
			    	 					}
	    	   		               	}
	        					}
	        				}
	        			}
	        		}.start();
	        	}
	        }else{
	        	result.setSuccess(BaseConstant.IS_YESNO_NO);
	            result.setInfo("附件不能为空");
	            return result;
	        }
			
			BaseLogUtils.info(logger, "add", "新增数据.[ids="+ids+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	 private void uploadAttchment(String attchmnt, DataResultVO result, Long id) {
        if(StringUtils.isNotEmpty(attchmnt)){
            //上传解析
            try{
                String cfgCd = McrBillMConstant.MCR_BILL_M_CFGCD;
                String cfgDtlCd = McrBillMConstant.MCR_BILL_M_CFGDTLCD_10;
                String tabNm = McrBillMConstant.MCR_BILL_M;
                String cfgOrgCd = McrBillMConstant.MCR_BILL_M_CFGORG;
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmntByOne(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, "小贷账单表附件!", null, null, false, cfgOrgCd);
                if(null == attchmntPass || attchmntPass == false){
                    result.setInfo(result.getInfo()+"-附件上传失败!");
                }/*else{
                	SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
                	qc.setPkId(id.toString());
                	this.sysUlFilesRecService.removeByCondition(qc);
                }*/
            }catch(Exception e){
                BaseLogUtils.error(logger, "uploadAttchment", result.getInfo()+"-附件上传失败!", e);
                result.setInfo(result.getInfo()+"-附件上传失败!");
            }
        }
    }
	 
	 /**
	     * 初始化列表
	     */
	    @SuppressWarnings("unchecked")
	    @RequestMapping(value = "/initUploadList.do", method = {RequestMethod.GET})
	    @ResponseBody
	    public Object initUploadList(HttpServletRequest request, HttpServletResponse response) {
	        String currentPage = request.getParameter("page");
	        String pageSize = request.getParameter("pagesize");
	        Pager page = new Pager();
	        if (StringUtils.isNotEmpty(currentPage)) {
	            page.setCurrentPage(Integer.parseInt(currentPage));
	        }

	        if (StringUtils.isNotEmpty(pageSize)) {
	            page.setEveryPage(Integer.parseInt(pageSize));
	        }

	        McrBillMQC qc = new McrBillMQC();
	        //设置查询条件？
	        String loanId = request.getParameter("loanId");
	        String accountId = request.getParameter("accountId");
	        if(StringUtils.isEmpty(loanId) && StringUtils.isEmpty(accountId)){
	        	return new ListPageVO<McrBillMVO>(null, 0);
	        } 
	        if(StringUtils.isNotEmpty(loanId)){
	        	qc.setLoanId(Long.parseLong(loanId));
	        } 
	        if(StringUtils.isNotEmpty(accountId)){
	        	 qc.setLoanAccountId(Long.parseLong(accountId));
	        }
	        List<String> stsCdList = new ArrayList<String>();
			stsCdList.add(McrBillMConstant.LOAN_STS_CD_4);	
			stsCdList.add(McrBillMConstant.LOAN_STS_CD_6);	
			stsCdList.add(McrBillMConstant.LOAN_STS_CD_7);
			qc.setLoanStsCdList(stsCdList);
	        qc.setIsDel(BaseConstant.IS_YESNO_NO);
	        qc.setIsPicture(McrBillMConstant.MCR_BILL_M_CFGCD);
	        page.setCondition(qc);

	        BaseLogUtils.info(logger, "initMcrBillMList", "初始化McrBillM列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
	        Pager pager = this.mcrBillMService.searchListPage(page);
	        List<McrBillMVO> list = (List<McrBillMVO>) pager.getResultList();
	        ListPageVO<McrBillMVO> listPage = new ListPageVO<McrBillMVO>(list, pager.getTotalCount());
	        return listPage;
	    }
	    
//云信账单上传失败处理------------------------------
	    
	    /**
	     * 云信账单上传失败列表页面
	     */
	    @RequestMapping(value = "/uploadFilesManageListPage.do", method = {RequestMethod.GET})
	    public ModelAndView uploadFilesManageListPage(HttpServletRequest request, HttpServletResponse response) {
	        BaseLogUtils.info(logger, "toListPage", "加载uploadFilesManageListPage列表页面.", CurrentThreadContext.getCurrentUserName());
	        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrUploadFilesManageList");
	        return mav;
	    }
	    
	    /**
	     * 初始化列表
	     */
	    @SuppressWarnings("unchecked")
	    @RequestMapping(value = "/initUploadFilesManageList.do", method = {RequestMethod.GET})
	    @ResponseBody
	    public Object initUploadFilesManageList(HttpServletRequest request, HttpServletResponse response) {
	        String currentPage = request.getParameter("page");
	        String pageSize = request.getParameter("pagesize");
	        cmm.mid.core.framework.page.Pager page = new  cmm.mid.core.framework.page.Pager();
	        if (StringUtils.isNotEmpty(currentPage)) {
	            page.setCurrentPage(Integer.parseInt(currentPage));
	        }
	        if (StringUtils.isNotEmpty(pageSize)) {
	            page.setEveryPage(Integer.parseInt(pageSize));
	        }
	        BaseLogUtils.info(logger, "initUploadFilesManageList", "初始化initUploadFilesManageList列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
            cmm.mid.core.framework.page.Pager pager = this.ynTrustApi.uploadFilesManageInfo(page);
	        List<UploadFilesManageDTO> list = (List<UploadFilesManageDTO>) pager.getResultList();
	        //添加证件号
            List<UploadFilesManageVo> resList = new ArrayList<UploadFilesManageVo>();
            if(CollectionUtils.isNotEmpty(list)){
                for(UploadFilesManageDTO uploadFilesManageDTO : list){
                    UploadFilesManageVo vo = new UploadFilesManageVo();
                    vo.setBillId(uploadFilesManageDTO.getBillId());
                    vo.setCstId(uploadFilesManageDTO.getCstId());
                    vo.setCstNm(uploadFilesManageDTO.getCstNm());
                    vo.setFundRasInsId(uploadFilesManageDTO.getFundRasInsId());
                    vo.setFundRasInsNm(uploadFilesManageDTO.getFundRasInsNm());
                    vo.setStatus(uploadFilesManageDTO.getStatus());
                    if(uploadFilesManageDTO.getCstId() != null){
                        CstBscInfoVO cstBscInfoVO = this.cstBscInfoService.selectById(uploadFilesManageDTO.getCstId());
                        if(cstBscInfoVO != null){
                            vo.setCertNo(cstBscInfoVO.getCertNo());
                        }
                    }
                    resList.add(vo);
                }
            }
	        ListPageVO<UploadFilesManageVo> listPage = new ListPageVO<UploadFilesManageVo>(resList, pager.getTotalCount());
	        return listPage;
	    }
	    
	    
	    /**
		 * 发送附件
		 */
		@RequestMapping(value = "/sendFileYNXT.do", method = {RequestMethod.POST })
		@ResponseBody
		public DataResultVO sendFileYNXT(HttpServletRequest request, HttpServletResponse response) throws BaseException {
			String id = request.getParameter("id");
			DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
			if(StringUtils.isEmpty(id)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				return result;
			}
			try {
				McrBillMVO vo = mcrBillMService.selectById(Long.parseLong(id));
				MessageDTO<String> message = ynTrustApi.uploadFiles(vo.getLoanId(), vo.getId(), vo.getCstId());
               	BaseLogUtils.info(logger, "sendFileYNXT", "调用云信上传附件接口返回数据:" + JSONObject.toJSONString(message), CurrentThreadContext.getCurrentUserName());
               	if(message.isSuccess()){
               		result.setInfo("发送成功");
               	}else{
               		result.setSuccess(BaseConstant.IS_YESNO_NO);
    				result.setInfo(message.getMessage());
               	}
				BaseLogUtils.info(logger, "sendFileYNXT", "调用云信上传附件接口.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}catch (BaseException ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(ex.getMessage());
				BaseLogUtils.info(logger, "sendFileYNXT", "调用云信上传附件接口失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
			}catch (Exception ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.error(logger, "sendFileYNXT", "调用云信上传附件接口失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
			}

			return result;
		}


    //-------------------------小贷回购


    /**
     * 判断所选数据是否可以回购
     */
    @RequestMapping(value = "/checkHuiGou.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object checkHuiGou(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String idS = request.getParameter("ids");//主键ID
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            final JSONArray ids = JSONArray.fromObject(idS);
            if(null != ids && !ids.isEmpty() && ids.isArray()){
                String loanChannel = "";
                String accountId = "";
                for (int i = 0; i < ids.size(); i++) {
                    if (StringUtils.isNotEmpty(ids.get(i).toString())) {
                        McrBillMVO vo = mcrBillMService.selectById(Long.valueOf(ids.get(i).toString()));
                        if(!vo.getLoanStsCd().equals(McrBillMConstant.LOAN_STS_CD_4)){
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("只有已放款账单才能回购");
                            return result;
                        }
                        if(StringUtils.isNotEmpty(vo.getLoanSource()) && vo.getLoanSource().equals(BaseConstant.IS_YESNO_YES_STR)){
                            if(StringUtils.isEmpty(loanChannel)){
                                loanChannel = vo.getLoanChannel();
                            }
                            if(StringUtils.isEmpty(accountId)){
                                accountId = vo.getLoanAccountId().toString();
                            }
                        }else{
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("只有资方账单才能回购");
                            return result;
                        }
                        if(!loanChannel.equals(vo.getLoanChannel())){
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("请选择同一个资方下的账单");
                            return result;
                        }
                        if(!accountId.equals(vo.getLoanAccountId().toString())){
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("请选择同一个资方下并且是同一期的账单");
                            return result;
                        }
                        
                        if("WKXT".equals(loanChannel)) {
                        	McrWaitBuyBackQC waitBuyBackQC = new McrWaitBuyBackQC();
                        	waitBuyBackQC.setPactNo(vo.getCrCntNo());
                        	waitBuyBackQC.setRepSts("00");
                        	List<McrWaitBuyBackVO> searchList = mcrWaitBuyBackService.searchList(waitBuyBackQC);
                        	if(CollectionUtils.isEmpty(searchList)) {
                        		result.setSuccess(BaseConstant.IS_YESNO_NO);
                        		result.setInfo("合同号:"+vo.getCrCntNo()+"回购台账不存在,不允许回购");
                        		return result;
                        	}
                        }
                        
                        //20200217增加回购校验；当天有还款不能回购
                        CapFundVfDtlQueryCondition capFundVfDtlQueryCondition = new CapFundVfDtlQueryCondition();
                        capFundVfDtlQueryCondition.setPaySchId(Long.valueOf(ids.get(i).toString()));
                        capFundVfDtlQueryCondition.setVfStsCd("2");
                        capFundVfDtlQueryCondition.setVfDt(new Date());
                        BaseLogUtils.info(logger, "checkHuiGou", "判断所选数据是否可以回购.CapFundVfDtlQueryCondition:" + JSONObject.toJSONString(capFundVfDtlQueryCondition), CurrentThreadContext.getCurrentUserName());
                        List<CapFundVfDtlDTO> list = capFundVfDtlApiService.searchCapFundVerificationList(capFundVfDtlQueryCondition);
                        BaseLogUtils.info(logger, "checkHuiGou", "判断所选数据是否可以回购.searchCapFundVerificationList:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
                        if(CollectionUtils.isNotEmpty(list)) {
                        	result.setSuccess(BaseConstant.IS_YESNO_NO);
                    		result.setInfo("当天有还款,不允许回购");
                    		return result;
                        }
                    }
                }
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("请至少选择一条数据");
                return result;
            }

            BaseLogUtils.info(logger, "checkHuiGou", "判断所选数据是否可以回购.[ids="+ids+"] DATA:" + JSONObject.toJSONString(idS), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "checkHuiGou", "判断所选数据是否可以回购失败.DATA:" + JSONObject.toJSONString(idS) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
        	ex.printStackTrace();
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "checkHuiGou", "判断所选数据是否可以回购失败.DATA:" + JSONObject.toJSONString(idS) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /*
     * 批量图片上传列表页面
     */
    @RequestMapping(value = "/huiGouListPage.do")
    public ModelAndView huiGouListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载mcrBillMHGList列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMHGList");
        String idS = request.getParameter("ids");//主键ID
        mav.addObject("idS", idS);
        return mav;
    }

    /**
     * 回购初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initHgList.do")
    @ResponseBody
    public Object initHgList(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功!");
        String idS = request.getParameter("ids");//主键ID
        try {
            JSONObject bean = new JSONObject();
            List<McrBillMDTO> voList = new ArrayList<McrBillMDTO>();
            Map<String, Object> map=new HashMap<>();
            final JSONArray ids = JSONArray.fromObject(idS);
            if(null != ids && !ids.isEmpty() && ids.isArray()){
                for (int i = 0; i < ids.size(); i++) {
                    String loanChannel = "";
                    if (StringUtils.isNotEmpty(ids.get(i).toString())) {
                        McrBillMVO vo = mcrBillMService.selectById(Long.valueOf(ids.get(i).toString()));
                        McrBillMQC condition = new McrBillMQC();
                        condition.setId(vo.getId());
                        List<McrBillMDTO> dtoList = this.publicMcrBillMApiService.searchNewCstSettleBillList(condition);
                        System.out.println(JSONObject.toJSONString(dtoList));
                        com.alibaba.fastjson.JSONArray billArray = new com.alibaba.fastjson.JSONArray();
                        if(CollectionUtils.isNotEmpty(dtoList)){
                            for(McrBillMDTO dto: dtoList){
                               /* billData.put("id", dto.getId());//账单ID
                                billData.put("capAmt", DecimalUtils.convertFenToYuan(dto.getArCapAmt()+dto.getArFineAmt()+dto.getArIntrAmt()));
                                billData.put("payDt", DateUtils.formatDateToString(dto.getPayDt(), DateUtils.YYYY_MM_DD_ZH));
                                billArray.add(billData);*/
                                dto.setYhTotalAmt(0l);
                                dto.setShTotalAmt(0l);
                                McrBillDQC qc = new McrBillDQC();
                                qc.setBillId(dto.getId());
                                qc.setIsDel(BaseConstant.IS_YESNO_NO);
                                List<McrBillDDTO> dList = publicMcrBillDApiService.searchMcrBillDList(qc);
                                if(CollectionUtils.isNotEmpty(dList)){
                                    for (McrBillDDTO bill : dList) {
                                        dto.setYhTotalAmt(dto.getYhTotalAmt()+bill.getCapAmt());
                                        dto.setShTotalAmt(dto.getShTotalAmt()+bill.getPaidCapAmt()+bill.getPaidIntrAmt());
                                    }
                                }
                                dto.setYhTotalAmt(dto.getYhTotalAmt()+dto.getArFineAmt()+dto.getArIntrAmt());
                                dto.setSettleAmt(dto.getArCapAmt()+dto.getArFineAmt()+dto.getArIntrAmt());
                                voList.add(dto);
                            }
                        }
                    }
                }
                bean.put("voList",voList);
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("账单id集合不能为空");
                return result;
            }
            map.put("bean", bean);
           // map.put("historyList", historyList);
            result.setData(map);
            BaseLogUtils.info(logger, "initHgList", "初始化huiGouListPage列表页面数据.DATA:" + JSONObject.toJSONString(ids), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getByCrId", "获取数据失败,回购初始化列表["+JSONObject.toJSONString(idS)+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
        	ex.printStackTrace();
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误!");
            BaseLogUtils.error(logger, "getByCrId", "获取数据失败,回购初始化列表["+JSONObject.toJSONString(idS)+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
		return result;
    }

    /**
     * 推送回购数据
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/hgSend.do")
    @ResponseBody
    public Object hgSend(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功!");
        int success = 0;// 成功数量
        int fail = 0;// 失败数量
        try {
			String buyBackIds = request.getParameter("idS");
			BaseLogUtils.info(logger, "hgSend", "推送回购数据idS:" + JSON.toJSONString(buyBackIds),	CurrentThreadContext.getCurrentUserName());
			final JSONArray ids = JSONArray.fromObject(buyBackIds);
			McrBillMQC bqc  = new McrBillMQC();
			bqc.setIdList(ids);
			List<McrBillMDTO> searchMcrBillMDTOList = publicMcrBillMApiService.searchMcrBillMDTOList(bqc);
			if(CollectionUtils.isNotEmpty(searchMcrBillMDTOList) && searchMcrBillMDTOList.size() >1) {
				for(McrBillMDTO mdto:searchMcrBillMDTOList) {
					if(StringUtils.isNotBlank(mdto.getSqBuyBackBatchNo())) {
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("批次回购数据中有已回购或回购失败数据,已回购过的订单请单独回购！");
						return result;
					}
				}
			}
			
			String sqBatchNo = DateUtils.getCurrentDateStr(DateUtils.YYYYMMDDHHMMSS) + LoanUtils.randomNum(6);// 生成回购批次号
			String loanChannel = "";
			if (null != ids && !ids.isEmpty() && ids.isArray()) {
				for (int i = 0; i < ids.size(); i++) {
					if (StringUtils.isNotEmpty(ids.get(i).toString())) {
						McrBillMVO vo = mcrBillMService.selectById(Long.valueOf(ids.get(i).toString()));
						McrBillMQC condition = new McrBillMQC();
						condition.setId(vo.getId());
						List<McrBillMDTO> dtoList = this.publicMcrBillMApiService.searchNewCstSettleBillList(condition);
						if (CollectionUtils.isNotEmpty(dtoList)) {
							for (McrBillMDTO dto : dtoList) {
								dto.setYhTotalAmt(0l);
								dto.setShTotalAmt(0l);
								McrBillDQC qc = new McrBillDQC();
								qc.setBillId(dto.getId());
								qc.setIsDel(BaseConstant.IS_YESNO_NO);
								List<McrBillDDTO> dList = publicMcrBillDApiService.searchMcrBillDList(qc);
								if (CollectionUtils.isNotEmpty(dList)) {
									for (McrBillDDTO bill : dList) {
										dto.setYhTotalAmt(dto.getYhTotalAmt() + bill.getCapAmt());
										dto.setShTotalAmt(dto.getShTotalAmt() + bill.getPaidCapAmt() + bill.getPaidIntrAmt());
									}
								}
								dto.setYhTotalAmt(dto.getYhTotalAmt() + dto.getArFineAmt() + dto.getArIntrAmt());
								dto.setSettleAmt(dto.getArCapAmt() + dto.getArFineAmt() + dto.getArIntrAmt());
								BaseLogUtils.info(logger, "hgSend", "推送回购数据dto:" + JSON.toJSONString(dto),	CurrentThreadContext.getCurrentUserName());
								if (StringUtils.isBlank(dto.getSqBuyBackBatchNo())) {
									dto.setSqBuyBackBatchNo(sqBatchNo);// 我司回购批次号
								} else {
									sqBatchNo = dto.getSqBuyBackBatchNo();
								}
								loanChannel = dto.getLoanChannel();
								if ("WKXT".equals(loanChannel)) {
									DataResultVO returnRes = this.sendWKBuyBack(result, dto);
									if (BaseConstant.IS_YESNO_YES == returnRes.getSuccess()) {
										success = success + 1;
									} else {
										fail = fail + 1;
									}
								} else {
									// 推送云信逾期数据
									DataResultVO sendYXBuyBackOverdue = this.sendYXBuyBackOverdue(result, dto);
									if (0 == sendYXBuyBackOverdue.getSuccess()) {
										return sendYXBuyBackOverdue;
									}
									// 回购
									List<RepurchaseDetail> getRepurchaseDetails = new ArrayList<RepurchaseDetail>();
									RepurchaseDetail detail = new RepurchaseDetail();
									detail.setCstId(dto.getCstId());
									detail.setCstNm(dto.getCstNm());
									detail.setBillId(dto.getId());
									detail.setLsCntNo(dto.getCrCntNo());
									String infLoanNo = publicMcrBillMApiService.queryInfTransLog(dto.getLoanId().toString(),
											dto.getId().toString(), "queryLoan", "1");
									BaseLogUtils.info(logger, "hgSend", "推送回购数据.合同唯一编号:" + JSONObject.toJSONString(infLoanNo),
											CurrentThreadContext.getCurrentUserName());
									if (StringUtils.isEmpty(infLoanNo)) {
										result.setSuccess(BaseConstant.IS_YESNO_NO);
										result.setInfo("推送回购数据.合同唯一编号为空 -客户名称:" + dto.getCstNm());
									}
									detail.setUniqueid(infLoanNo);// 合同唯一编号
									detail.setPrincipal(new BigDecimal(DecimalUtils.convertFenToYuan(dto.getArCapAmt())).setScale(2,BigDecimal.ROUND_HALF_UP));
									detail.setInterest(new BigDecimal(DecimalUtils.convertFenToYuan(dto.getArIntrAmt())).setScale(2,BigDecimal.ROUND_HALF_UP));
									detail.setPenaltyInterest(new BigDecimal(DecimalUtils.convertFenToYuan(dto.getArFineAmt())).setScale(2, BigDecimal.ROUND_HALF_UP));
									detail.setAmount(new BigDecimal(DecimalUtils.convertFenToYuan(dto.getSettleAmt())).setScale(2,BigDecimal.ROUND_HALF_UP));
									getRepurchaseDetails.add(detail);
									boolean sendYXBuyBack = this.sendYXBuyBack(dto, getRepurchaseDetails);
									BaseLogUtils.info(logger, "hgSend", "云信回购id"+dto.getId() +",结果：" + sendYXBuyBack,CurrentThreadContext.getCurrentUserName());
									if (sendYXBuyBack) {
										success = success + 1;
									} else {
										fail = fail + 1;
									}
								}
								
							}
						}
					}
				}
			}
				
			// 回购批量记录
			McrBillBuyBackRecordDTO buyBackDto = new McrBillBuyBackRecordDTO();
			McrBillBuyBackRecordQC buyBackQc = new McrBillBuyBackRecordQC();
			buyBackQc.setBatchNo(sqBatchNo);
			List<McrBillBuyBackRecordDTO> buyBackList = mcrBillBuyBackRecordApiService.searchList(buyBackQc);
			if (CollectionUtils.isNotEmpty(buyBackList)) {
				buyBackDto = buyBackList.get(0);
				//buyBackDto.setTotalNumber(Long.valueOf(success+fail));
				buyBackDto.setSuccessNumber(buyBackDto.getSuccessNumber() + Long.valueOf(success));
				buyBackDto.setFailNumber(buyBackDto.getFailNumber() - Long.valueOf(success));
				buyBackDto.setMdfTm(new Date());
				logger.info("McrBillMController.hgSend>>modify>>buyBackDto:" + JSON.toJSONString(buyBackDto));
				mcrBillBuyBackRecordApiService.modify(buyBackDto);
			} else {
				buyBackDto.setTotalNumber(Long.valueOf(success+fail));
				buyBackDto.setSuccessNumber(Long.valueOf(success));
				buyBackDto.setFailNumber(Long.valueOf(fail));
				buyBackDto.setBatchNo(sqBatchNo);
				buyBackDto.setLoanChannel(loanChannel);
				if ("WKXT".equals(loanChannel)) {
					buyBackDto.setLoanName("五矿信托");
				} else if ("YNXT".equals(loanChannel)) {
					buyBackDto.setLoanName("云南信托");
				}
				buyBackDto.setCrtTm(new Date());
				logger.info("McrBillMController.hgSend>>add>>buyBackDto:" + JSON.toJSONString(buyBackDto));
				mcrBillBuyBackRecordApiService.add(buyBackDto);
			}
			BaseLogUtils.info(logger, "hgSend", "推送回购数据完成:" + JSONObject.toJSONString(buyBackIds),CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "hgSend", "推送回购数据 失败." + ex.getMessage(),	CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "hgSend", "推送回购数据异常" + ex.getMessage(),CurrentThreadContext.getCurrentUserName());
		}
        result.setInfo("回购成功:"+success+"笔,回购失败:"+fail+"笔");
        return result;
    }

    /**
     * 三方机构转我司 重置属性
     * @param mcrBillMDTO
     * @return
     * @throws BaseException
     */
    private McrBillMDTO reSetMcrBillMDTO(McrBillMDTO mcrBillMDTO) throws BaseException{
        mcrBillMDTO.setLoanSource(McrBillMConstant.LOAN_SOURCE_0);
        mcrBillMDTO.setLoanId(null);
        mcrBillMDTO.setLoanName(null);
        mcrBillMDTO.setLoanChannel(null);
        mcrBillMDTO.setLoanAccountId(null);
        mcrBillMDTO.setLoanAccountNm(null);
        mcrBillMDTO.setIsInform(1);
        int count = this.publicMcrBillMApiService.reSetMcrBillMDTO(mcrBillMDTO);
        BaseLogUtils.info(logger, "reSetMcrBillMDTO", "三方机构转我司.重置属性结果：" + count + "-账单：" + mcrBillMDTO.getId());
        return mcrBillMDTO;
    }

    /**
     * 推送还款计划接口
     */
    @RequestMapping(value = "/pushRepaymentPlan.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object pushRepaymentPlan(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "pushRepaymentPlan", "推送还款计划接口.开始时间["+startTm+"]");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            DataResultDTO dataResultDTO = mcrBillMService.pushRepaymentPlan();
            if(dataResultDTO ==null || dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_NO){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("推送划款计划失败");
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "pushRepaymentPlan", ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "pushRepaymentPlan", ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "pushRepaymentPlan", "推送还款计划接口.耗时："+(endTm-startTm));
        return result;
    }

    /**
     * 人工处理放款结果
     */
    @RequestMapping(value = "/editLoanStsCdType.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object editLoanStsCdType(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果.开始时间["+startTm+"]");
        String id = request.getParameter("id");
        String cstTypCd = request.getParameter("cstTypCd");
        String loanStsCd = request.getParameter("loanStsCd");
        BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果,参数.[id="+id+"]"+"[cstTypCd="+cstTypCd+"]"+"[loanStsCd="+loanStsCd+"]", CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(cstTypCd) || StringUtils.isEmpty(loanStsCd)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果,参数不全.[id="+id+"]"+"[cstTypCd="+cstTypCd+"]"+"[loanStsCd="+loanStsCd+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            McrBillMDTO dto = new McrBillMDTO();
            dto.setId(Long.valueOf(id));
            dto.setLoanStsCd(loanStsCd);
            DataResultDTO dataResultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES,"成功");
            if(cstTypCd.equals(McrCstCrLimConstant.MCR_CST_TYP_CD_LGS)){
                dataResultDTO = this.publicMcrCstCrLimApiService.manLoanProcessingLgs(dto);
            }else{
                dataResultDTO = this.publicMcrCstCrLimApiService.manLoanProcessing(dto);
            }
            if(dataResultDTO ==null || dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_NO){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(dataResultDTO.getInfo());
                BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果失败.[id="+id+"] DATA:" + JSONObject.toJSONString(dataResultDTO), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果成功.[id="+id+"] DATA:" + JSONObject.toJSONString(dataResultDTO), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果失败.[id="+id+"]"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "editLoanStsCdType", "人工处理放款结果失败.[id="+id+"]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }
    
    /**
     * 
     * @Title: sendWKBuyBack   
     * @Description: 推送五矿回购信息
     * @param: @param result
     * @param: @return      
     * @return: DataResultVO      
     * @throws
     */
    public DataResultVO sendWKBuyBack(DataResultVO result,McrBillMDTO dto) {
    	try {
    		BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据.账单明细：" + JSONObject.toJSONString(dto), CurrentThreadContext.getCurrentUserName());
    		
    		McrWaitBuyBackQC waitBuyBackQC = new McrWaitBuyBackQC();
            waitBuyBackQC.setPactNo(dto.getCrCntNo());
            waitBuyBackQC.setRepSts("00");
            List<McrWaitBuyBackVO> searchList = mcrWaitBuyBackService.searchList(waitBuyBackQC);
            if(CollectionUtils.isEmpty(searchList)) {
             	result.setSuccess(BaseConstant.IS_YESNO_NO);
	            result.setInfo("合同号:"+dto.getCrCntNo()+"不允许回购");
	            return result;
            }else {
            	
            	Long repPrcp = searchList.get(0).getRepPrcp();//债转本金
            	Long repInte = searchList.get(0).getRepInte();//债转利息
            	Long repFine = searchList.get(0).getRepFine();//债转罚息
            	//订单状态为结清时回购状态置为失败
            	if(McrBillMConstant.LOAN_STS_CD_6.equals(dto.getLoanStsCd()) || McrBillMConstant.LOAN_STS_CD_7.equals(dto.getLoanStsCd()) || McrBillMConstant.LOAN_STS_CD_8.equals(dto.getLoanStsCd()) ) {
            		logger.info("订单id:"+dto.getId()+" 状态为结清,回购失败");
            		dto.setRepSts("03");
            		dto.setBuyBackFailReason("债转失败已结清");
            		this.publicMcrBillMApiService.modifyMcrBillM(dto);
            		
            		this.addMcrInformTransfer(dto,repPrcp,repInte,repFine);
            		return result;
            	}
            	BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据>>>ArCapAmt:" + dto.getArCapAmt()+"repPrcp:"+repPrcp, CurrentThreadContext.getCurrentUserName());
            	if(dto.getArCapAmt().longValue() != repPrcp.longValue()) {
            		dto.setBuyBackFailReason("与资方回购本金不一致,资方本金"+DecimalUtils.convertFenToYuan(repPrcp));//失败原因
            		dto.setRepSts("03");
					this.publicMcrBillMApiService.modifyMcrBillM(dto);
					
					this.addMcrInformTransfer(dto,repPrcp,repInte,repFine);
            		result.setSuccess(BaseConstant.IS_YESNO_NO);
    	            result.setInfo("合同号:"+dto.getCrCntNo()+"与资方回购本金不一致,资方本金:"+DecimalUtils.convertFenToYuan(repPrcp));
    	            return result;
            	}
            	if(dto.getArIntrAmt().longValue() != repInte.longValue()) {
            		dto.setRepSts("03");
            		dto.setBuyBackFailReason("与资方回购利息不一致,资方利息"+DecimalUtils.convertFenToYuan(repInte));//失败原因
					this.publicMcrBillMApiService.modifyMcrBillM(dto);
					
					this.addMcrInformTransfer(dto,repPrcp,repInte,repFine);
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("合同号:"+dto.getCrCntNo()+"与资方回购利息不一致,资方利息:"+DecimalUtils.convertFenToYuan(repInte));
    	            return result;
            	}
            	 
            }
    		
    		List<PrepaymentDTO> prepaymentDTOS = Lists.newArrayList();
    		PrepaymentDTO prepaymentDto = new PrepaymentDTO();
    		McrLoanAccountQC condition = new McrLoanAccountQC();
    		condition.setIsDel(BaseConstant.IS_YESNO_NO);
    		condition.setIsValid(BaseConstant.IS_YESNO_YES);
    		condition.setLoanChannel("WKXT");
    		List<McrLoanAccountDTO> dtoList = publicMcrLoanAccountApiService.searchList(condition);
    		if(CollectionUtils.isNotEmpty(dtoList)) {
    			prepaymentDto.setFundRasInsId(dtoList.get(0).getLoanId());//机构ID
    			prepaymentDto.setCstId(dto.getCstId());//客户ID
    			prepaymentDto.setBillId(dto.getId());//账单ID
    			prepaymentDto.setLsCntNo(dto.getCrCntNo());//我司合同号
    			prepaymentDto.setProjNo(dtoList.get(0).getProjectCode());//项目号
    			prepaymentDto.setRepPrcp(dto.getArCapAmt());//债转本金
    			prepaymentDto.setRepInte(dto.getArIntrAmt());//债转利息
    			prepaymentDto.setRepFine(dto.getArFineAmt());//债转罚息
    			prepaymentDTOS.add(prepaymentDto);
    			BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据>>>>>>：" + JSONObject.toJSONString(prepaymentDTOS), CurrentThreadContext.getCurrentUserName());
    			MessageDTO<AuditResult> prepaymentMessage = wkxtApiService.prepayment(prepaymentDTOS);
    			BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据返回结果>>>>>>：" + JSONObject.toJSONString(prepaymentMessage), CurrentThreadContext.getCurrentUserName());
    			
    			if(prepaymentMessage!=null && prepaymentMessage.isSuccess() && null != prepaymentMessage.getData() && prepaymentMessage.getData().equals(InterfaceConstants.AuditResult.pass)){
    				BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据.推送明细成功!.账单明细：" + JSONObject.toJSONString(dto.getId()), CurrentThreadContext.getCurrentUserName());
    				
    				this.addMcrInformTransfer(dto,dto.getArCapAmt(),dto.getArIntrAmt(),dto.getArFineAmt());//增加回购明细
    				
    				dto.setLoanSource(McrBillMConstant.LOAN_SOURCE_0);
    				dto.setLoanId(null);
    				dto.setLoanName(null);
    				dto.setLoanChannel(null);
    				dto.setLoanAccountId(null);
    				dto.setLoanAccountNm(null);
    				dto.setIsInform(1);
    				this.publicMcrBillMApiService.modifyMcrBillM(dto);
    				
    				publicMcrBillMApiService.wkPrepaymentResult(dto.getId(), prepaymentMessage.getCode(),dto.getSqBuyBackBatchNo());
    			}else {
    				String message = prepaymentMessage.getMessage();//失败原因
    				if(message.length() > 0) {
    					McrBillMDTO billDto = new  McrBillMDTO();
    					billDto.setId(dto.getId());
    					if(message.length() > 1000) {
    						message = message.substring(0,999);
    					}
    					billDto.setBuyBackFailReason(message);//失败原因
    					billDto.setSqBuyBackBatchNo(dto.getSqBuyBackBatchNo());
    					billDto.setRepSts("03");
    					
    					this.addMcrInformTransfer(dto,dto.getArCapAmt(),dto.getArIntrAmt(),dto.getArFineAmt());//增加回购明细
    					this.publicMcrBillMApiService.modifyMcrBillM(billDto);
    				}
    				
    				BaseLogUtils.info(logger, "sendWKBuyBack", "五矿推送回购数据.推送明细失败!.账单明细：" + JSONObject.toJSONString(dto.getId()), CurrentThreadContext.getCurrentUserName());
    				result.setSuccess(BaseConstant.IS_YESNO_NO);
    				result.setInfo("推送回购数据.推送罚息明细失败!.账单明细："+dto.getId());
    				return result;
    			}
    		}else {
    			BaseLogUtils.info(logger, "sendWKBuyBack", "五矿基本信息为空,无法获取机构,项目号等信息！");
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo("五矿基本信息为空,无法获取机构,项目号等信息！");
    			return result;
    		}
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误!");
            BaseLogUtils.error(logger, "sendWKBuyBack", "推送回购数据失败:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
    	
    	return result;
    }
    
    /**
     * 
     * @Title: sendYXBuyBackOverdue   
     * @Description: 推送云信回购逾期数据
     * @param: @param result
     * @param: @param dto
     * @param: @return      
     * @return: DataResultVO      
     * @throws
     */
    public DataResultVO sendYXBuyBackOverdue(DataResultVO result,McrBillMDTO dto) {
    	BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "云信推送回购逾期数据.账单明细start：" + JSONObject.toJSONString(dto), CurrentThreadContext.getCurrentUserName());
    	try {
    		//单笔逾期罚息
            List<CapOverdueDtlDTO> capOverdueDtlList = new ArrayList<CapOverdueDtlDTO>();
            CapOverdueDtlCondition capOverdueDtlQC = new CapOverdueDtlCondition();
            capOverdueDtlQC.setPaySchId(dto.getId());
            capOverdueDtlQC.setIsDel(BaseConstant.IS_YESNO_NO);
            capOverdueDtlQC.setPenaltyDt(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD));
//            List<CapOverdueDtlBean> dtlList = publicMcrBillMApiService.queryCapOverdueDtlDTO(capOverdueDtlQC);
            List<CapOverdueInfoBean> dtlList = publicMcrBillMApiService.queryCapOverdueInfoDTO(capOverdueDtlQC);
            BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "推送云信回购数据.推送罚息明细.罚息数据明细:" + JSONObject.toJSONString(dtlList), CurrentThreadContext.getCurrentUserName());
            McrBillMQC mcrBillMQC = new McrBillMQC();
            mcrBillMQC.setId(dto.getId());
            McrBillMDTO billM = publicMcrBillMApiService.searchMcrBillMList(mcrBillMQC).get(0);
            if (CollectionUtils.isNotEmpty(dtlList)) {
                for (CapOverdueInfoBean dtl : dtlList) {
                    McrBillDQC billDQC = new McrBillDQC();
                    billDQC.setBillId(dto.getId());
                    billDQC.setPayPd(dtl.getPayPd());
                    McrBillDDTO billD = publicMcrBillDApiService.searchMcrBillDList(billDQC).get(0);
                    CapOverdueDtlDTO overdueDtlDTO = new CapOverdueDtlDTO();
                    overdueDtlDTO.setId(billD.getId());
                    overdueDtlDTO.setBillId(dtl.getPaySchId());
                    overdueDtlDTO.setPayPd(dtl.getPayPd().intValue());
                    overdueDtlDTO.setPaidUpAmt(new BigDecimal(dtl.getPenaltyAmount()+(dtl.getPayAmount() == null ? 0 : dtl.getPayAmount()) + (dtl.getBeforePayAmount() == null ? 0 : dtl.getBeforePayAmount())));
                    BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "推送云信回购数据.推送罚息明细.罚息数据明细.罚息(paidUpAmt):" + overdueDtlDTO.getPaidUpAmt(), CurrentThreadContext.getCurrentUserName());
                    overdueDtlDTO.setFundRasInsId(billM.getLoanId().longValue());
                    overdueDtlDTO.setFundRasInsNm(billM.getLoanName());
                    overdueDtlDTO.setLsCntNo(billM.getCrCntNo());
                    overdueDtlDTO.setCstId(billM.getCstId());
                    overdueDtlDTO.setCstNm(billM.getCstNm());
                    String loanNo =  publicMcrBillMApiService.queryInfTransLog(billM.getLoanId().toString(), billM.getId().toString(),"createPayPlan","0000");
                    BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "推送云信回购数据.推送罚息明细.合同唯一编号:" + JSONObject.toJSONString(loanNo), CurrentThreadContext.getCurrentUserName());
                    if(StringUtils.isEmpty(loanNo)){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("推送罚息明细.合同唯一编号为空 -客户名称:"+dto.getCstNm());
                        return result;
                    }
                    overdueDtlDTO.setLoanNo(loanNo);
                    capOverdueDtlList.add(overdueDtlDTO);
                }
            }
            if(CollectionUtils.isNotEmpty(capOverdueDtlList)){
                MessageDTO<String> message = ynTrustApi.repurchaseUpdateOverdue(capOverdueDtlList);
                BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "推送云信回购数据.推送罚息明细.返回数据:" + JSONObject.toJSONString(message), CurrentThreadContext.getCurrentUserName());
                if(message == null || message.isSuccess() == false){
                	String returnMsg = message.getMessage();
                	if(returnMsg.length() > 0) {
                		McrBillMDTO billDto = new  McrBillMDTO();
                		billDto.setId(dto.getId());
                		if(returnMsg.length() > 1000) {
                			returnMsg = returnMsg.substring(0,999);
    					}
    					billDto.setBuyBackFailReason(returnMsg);//失败原因
    					billDto.setRepSts("03");
    					this.addMcrInformTransfer(dto,dto.getArCapAmt(),dto.getArIntrAmt(),dto.getArFineAmt());//增加回购明细
                		this.publicMcrBillMApiService.modifyMcrBillM(billDto);
                	}
                	
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("推送回购数据.推送罚息明细失败!.账单明细："+dto.getId());
                    BaseLogUtils.info(logger, "sendYXBuyBackOverdue", "推送云信回购数据.推送罚息明细失败!.账单明细：" + JSONObject.toJSONString(dto.getId()), CurrentThreadContext.getCurrentUserName());
                    return result;
                }
            }
    		
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误!");
            BaseLogUtils.error(logger, "sendYXBuyBackOverdue", "推送云信回购-逾期数据失败:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
    	
    	return result;
    }
    
    /**
     * 
     * @Title: sendYXBuyBack   
     * @Description: 推送云信回购数据
     * @param: @param result
     * @param: @param hgList
     * @param: @param getRepurchaseDetails
     * @param: @return      
     * @return: DataResultVO      
     * @throws
     */
    public boolean sendYXBuyBack(McrBillMDTO hgDTO,List<RepurchaseDetail> getRepurchaseDetails) {
    	BaseLogUtils.info(logger, "sendYXBuyBack", "云信推送回购数据.账单明细start",  CurrentThreadContext.getCurrentUserName());
    	boolean result = true;
    	try {
    		Long insId = hgDTO.getLoanAccountId();
        	String insNm = hgDTO.getLoanName();
        	long accountId = hgDTO.getLoanAccountId();
    		
    		RepurchaseDTO sendDto = new RepurchaseDTO();
    		McrLoanAccountDTO accountDto = publicMcrLoanAccountApiService.selectMcrLoanAccountDTOById(accountId);
            String productCode = accountDto.getProductCode();
            sendDto.setFundRasInsId(insId);//机构id
            sendDto.setFundRasInsNm(insNm);//机构名称
            sendDto.setProductCode(productCode);//产品编码
            sendDto.setRepurchaseDetails(getRepurchaseDetails);
            MessageDTO<String> message = ynTrustApi.repurchase(sendDto);
            BaseLogUtils.info(logger, "sendYXBuyBack", "推送云信回购数据.返回数据:" + JSONObject.toJSONString(message), CurrentThreadContext.getCurrentUserName());
            if(message!=null && message.isSuccess() == true && message.getCode().equals("0000")){
                BaseLogUtils.info(logger, "sendYXBuyBack", "操作成功.成功账单Id:"+JSONObject.toJSONString(message.getDatas()), CurrentThreadContext.getCurrentUserName());
                if(message.getDatas()!=null && message.getDatas().size()>0){
                	this.addMcrInformTransfer(hgDTO,hgDTO.getArCapAmt(),hgDTO.getArIntrAmt(),hgDTO.getArFineAmt());//增加回购明细
                    
                	hgDTO.setSqBuyBackBatchNo(hgDTO.getSqBuyBackBatchNo());
                	hgDTO.setRepSts("02");
                    reSetMcrBillMDTO(hgDTO);
                }else {
                	this.addMcrInformTransfer(hgDTO,hgDTO.getArCapAmt(),hgDTO.getArIntrAmt(),hgDTO.getArFineAmt());//增加回购明细
                	hgDTO.setRepSts("03");
                	this.publicMcrBillMApiService.modifyMcrBillM(hgDTO);
                	result = false;
                	BaseLogUtils.info(logger, "sendYXBuyBack", "回购申请接口操作失败:"+hgDTO.getId(), CurrentThreadContext.getCurrentUserName());
                }
            }else{
            	this.addMcrInformTransfer(hgDTO,hgDTO.getArCapAmt(),hgDTO.getArIntrAmt(),hgDTO.getArFineAmt());//增加回购明细
            	hgDTO.setRepSts("03");
            	this.publicMcrBillMApiService.modifyMcrBillM(hgDTO);
            	result = false;
                BaseLogUtils.info(logger, "sendYXBuyBack", "回购申请接口 返回失败:"+hgDTO.getId(), CurrentThreadContext.getCurrentUserName());
            }
		} catch (Exception e) {
			result = false;
            BaseLogUtils.error(logger, "sendYXBuyBack", "推送云信回购数据失败:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
    	BaseLogUtils.info(logger, "sendYXBuyBack", "云信推送回购数据.账单明细id:"+hgDTO.getId()+","+result,  CurrentThreadContext.getCurrentUserName());
    	return result;
    }

    /**
     * 
     * @Title: addMcrInformTransfer   
     * @Description: 增加回购明细  
     * @param: @param dto      
     * @return: void      
     * @throws
     */
    public void addMcrInformTransfer(McrBillMDTO dto,long yhCapAmt,long yhIntrAmt,long yhPenaltyAmt) {
    	BaseLogUtils.info(logger, "addMcrInformTransfer", "McrBillMController.addMcrInformTransfer.start:" + JSONObject.toJSONString(dto), CurrentThreadContext.getCurrentUserName());
        CstBscInfoVO cstVo = cstBscInfoService.selectById(dto.getCstId());
        McrLoanAccountDTO loanAccountDTO = publicMcrLoanAccountApiService.selectMcrLoanAccountDTOById(dto.getLoanAccountId());

        McrInformTransferQC transferQc = new McrInformTransferQC();
        transferQc.setCrCntNo(dto.getCrCntNo());
        List<McrInformTransferDTO> searchMcrInformTransferDTOList = publicMcrInformTransferApiService.searchMcrInformTransferDTOList(transferQc);
        McrInformTransferDTO ferDto = new McrInformTransferDTO();
        
        
        if(CollectionUtils.isNotEmpty(searchMcrInformTransferDTOList)) {
        	ferDto  = searchMcrInformTransferDTOList.get(0);
        	ferDto.setCapAmt(dto.getArCapAmt());
            ferDto.setIntrAmt(dto.getArIntrAmt());
            ferDto.setPenaltyAmt(dto.getArFineAmt());
            ferDto.setTotalAmt(dto.getSettleAmt());
            ferDto.setYhCapAmt(yhCapAmt);
            ferDto.setYhIntrAmt(yhIntrAmt);
            ferDto.setYhPenaltyAmt(yhPenaltyAmt);
            ferDto.setYhTotalAmt(yhCapAmt + yhIntrAmt + yhPenaltyAmt);
        	ferDto.setMdfTm(new Date());
        	publicMcrInformTransferApiService.modifyMcrInformTransferDTO(ferDto);
        }else {
        	ferDto.setCapAmt(dto.getArCapAmt());
            ferDto.setIntrAmt(dto.getArIntrAmt());
            ferDto.setPenaltyAmt(dto.getArFineAmt());
            ferDto.setTotalAmt(dto.getSettleAmt());
            ferDto.setYhCapAmt(yhCapAmt);
            ferDto.setYhIntrAmt(yhIntrAmt);
            ferDto.setYhPenaltyAmt(yhPenaltyAmt);
            ferDto.setYhTotalAmt(yhCapAmt + yhIntrAmt + yhPenaltyAmt);
        	
        	ferDto.setCrCntNo(dto.getCrCntNo());
        	ferDto.setCstNm(dto.getCstNm());
        	ferDto.setPrjId(dto.getId());
        	if(cstVo!=null){
        		ferDto.setCertNo(cstVo.getCertNo());
        	}
        	ferDto.setLoanChannel(loanAccountDTO.getAccountName());
        	ferDto.setToUs(new Date());
        	ferDto.setOriBusType(0l);
        	ferDto.setNowBusType(1l);
        	ferDto.setToUsReason("回购");
        	ferDto.setIsSloan(BaseConstant.IS_YESNO_YES);
        	ferDto.setBusUnit(1l);
        	ferDto.setCrtTm(new Date());
        	ferDto.setLoanAccountId(dto.getLoanAccountId());//放款账号ID
        	ferDto.setRepoSubject(loanAccountDTO.getRepoSubject());//回购主体
        	publicMcrInformTransferApiService.addInformTransfer(ferDto);
        }
        BaseLogUtils.info(logger, "addMcrInformTransfer", "McrBillMController.addMcrInformTransfer.end", CurrentThreadContext.getCurrentUserName());
    }
    

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListVliPage.do", method = {RequestMethod.GET})
    public ModelAndView toListVliPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListLgsPage", "加载McrBillM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("mcr/mcrBillM/mcrBillMVliList");

        //查询数据字典
        List<KeyValueVO> loanBizTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        List<KeyValueVO> crTypCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_CR_TYP_CD);
        List<KeyValueVO> loanStsCdList = this.mcrBillMService.searchCdList(McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        //业务类型
        mav.addObject("loanBizTypCdList", JSON.toJSONString(loanBizTypCdList));
        //贷款类型
        mav.addObject("crTypCdList", JSON.toJSONString(crTypCdList));
        //贷款状态
        mav.addObject("loanStsCdList", JSON.toJSONString(loanStsCdList));

        return mav;
    }


    /**
     * 车贷分期初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initVliList.do")
    @ResponseBody
    public Object initVliList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        McrBillMQC qc = new McrBillMQC();
        //设置查询条件？
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotBlank(cstNm)) {
            qc.setCstNm(cstNm);
        }
        String cstId = request.getParameter("cstId");
        if (StringUtils.isNotBlank(cstId)) {
            qc.setCstId(Long.valueOf(cstId));
        }
        String crCntNo = request.getParameter("crCntNo");
        if(StringUtils.isNotBlank(crCntNo)){
            qc.setCrCntNo(crCntNo);
        }
        String loanBizTypCd = request.getParameter("loanBizTypCd");
        if(StringUtils.isNotBlank(loanBizTypCd)){
            qc.setLoanBizTypCd(loanBizTypCd);
        }
        String loanStsCd = request.getParameter("loanStsCd");
        if(StringUtils.isNotBlank(loanStsCd)){
            qc.setLoanStsCd(loanStsCd);
        }
        String crTypCd = request.getParameter("crTypCd");
        if(StringUtils.isNotBlank(crTypCd)){
            qc.setCrTypCd(crTypCd);
        }
        String paySchId = request.getParameter("paySchId");
        if(StringUtils.isNotBlank(paySchId)){
            qc.setPaySchId(paySchId);
        }
        String isSuc = request.getParameter("isSuc");
        if(StringUtils.isNotBlank(isSuc)){
            qc.setIsSuc(isSuc);
        }
        qc.setOpUsrId(CurrentThreadContext.getCurrentUserId());
        String remarkCode = request.getParameter("remarkCode");
        if(StringUtils.isNotEmpty(remarkCode)){
            qc.setRemarkCode(remarkCode);
        }
        qc.setCstTypCd(McrCstCrLimConstant.MCR_CST_TYP_CD_VLI);
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        page.setCondition(qc);
        BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期列表页面参数.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.mcrBillMService.searchListPage(page);
        BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期列表页面数据.DATA:" + JSONObject.toJSONString(pager), CurrentThreadContext.getCurrentUserName());
        List<McrBillMVO> list = (List<McrBillMVO>) pager.getResultList();
        if(CollectionUtils.isNotEmpty(list)){
            for(McrBillMVO vo : list){
                McrLoanRecQc mcrLoanRecQc = new McrLoanRecQc();
                mcrLoanRecQc.setIsDel(BaseConstant.IS_YESNO_NO);
                mcrLoanRecQc.setBillId(vo.getId());
                List<McrLoanRecDTO> mcrLoanRecDTOS = publicMcrLoanRecApiService.selectList(mcrLoanRecQc);
                BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期还款数据:" + JSONObject.toJSONString(mcrLoanRecDTOS), CurrentThreadContext.getCurrentUserName());
                vo.setPaySchId(mcrLoanRecDTOS.get(0).getPaySchId());
                vo.setPayCrPd(mcrLoanRecDTOS.get(0).getPayCrPd());
                vo.setIsSuc(mcrLoanRecDTOS.get(0).getIsSuc().toString());
                vo.setVliStatus(mcrLoanRecDTOS.get(0).getStatus());
                vo.setFundNo("资金编号");
                vo.setDeductionNo("扣款次数");
                BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期扣款次数参数:" + mcrLoanRecDTOS.get(0).getPaySchNo()+";"+vo.getId(), CurrentThreadContext.getCurrentUserName());
                DataResultDTO dataResultDTO = cmmInstallmentApiService.orderFailNumQuery(mcrLoanRecDTOS.get(0).getPaySchNo(), vo.getId().toString());
                BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期查询扣款次数返回结果:" + JSONObject.toJSONString(dataResultDTO), CurrentThreadContext.getCurrentUserName());
                if(dataResultDTO!= null && dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_YES){
                    Map<String, Object> map = (Map<String, Object>) dataResultDTO.getData();
                    if(!map.isEmpty()){
                        Integer failNum = (Integer) map.get("failNum");
                        vo.setDeductionNo(failNum.toString());
                    }
                }
                PrjPrdPaySchDQueryCondition conditon = new PrjPrdPaySchDQueryCondition();
                conditon.setPaySchId(Long.valueOf(mcrLoanRecDTOS.get(0).getPaySchId()));
                conditon.setPayPd(Long.valueOf(mcrLoanRecDTOS.get(0).getPayCrPd()));
                BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期查询资金编号参数:" + JSONObject.toJSONString(conditon), CurrentThreadContext.getCurrentUserName());
                DataResultDTO vehResultDTO = vehLoanInstallmentApiService.selectFundByPayschIdPaypd(conditon);
                BaseLogUtils.info(logger, "initMcrBillMList", "车贷分期查询资金编号返回结果.DATA:" + JSONObject.toJSONString(vehResultDTO), CurrentThreadContext.getCurrentUserName());
                if(vehResultDTO!=null && vehResultDTO.getSuccess() == BaseConstant.IS_YESNO_YES){
                    List<VehLoanDTO> vehLoanDTOS = (List<VehLoanDTO>) vehResultDTO.getData();
                    if(CollectionUtils.isNotEmpty(vehLoanDTOS)){
                        vo.setFundNo(vehLoanDTOS.get(0).getFundCode());
                        vo.setFundId(vehLoanDTOS.get(0).getFundId());
                    }
                }

            }
        }
        ListPageVO<McrBillMVO> listPage = new ListPageVO<McrBillMVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 重置扣款流程
     */
    @RequestMapping(value = "/sendDeduction.do")
    @ResponseBody
    public Object sendDeduction(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "sendDeduction", "重置扣款流程,主键不存在.id="+id+"", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            McrBillMDTO mcrBillMDTO = publicMcrBillMApiService.selectMcrBillMById(Long.valueOf(id));
            McrLoanRecQc qc = new McrLoanRecQc();
            qc.setBillId(mcrBillMDTO.getId());
            List<McrLoanRecDTO> mcrLoanRecDTOS = publicMcrLoanRecApiService.selectList(qc);
            BaseLogUtils.info(logger, "sendDeduction", "重置扣款流程.id="+id+" mcrLoanRecDTOS:" + JSONObject.toJSONString(mcrLoanRecDTOS), CurrentThreadContext.getCurrentUserName());
            McrLoanRecDTO mcrLoanRecDTO = mcrLoanRecDTOS.get(0);
            //mcrLoanRecDTO.setIsSuc(Integer.valueOf(McrLoanRecConstant.IS_SUC_10));
            mcrLoanRecDTO.setStatus(BaseConstant.IS_YESNO_NO);
            mcrLoanRecDTO.setDedNum("0");
            mcrLoanRecDTO.setQueryNum("0");
            mcrLoanRecDTO.setMdfTm(new Date());
            publicMcrLoanRecApiService.modifyMcrLoanRecDTO(mcrLoanRecDTO);
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "sendDeduction", "重置扣款流程.id="+id + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "sendDeduction", "重置扣款流程.id="+id + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }
}

